import React, { useState, useEffect } from 'react';
import ColorThief from 'colorthief';
import './GradientBackground.scss';

const GradientBackgroundCss = ({ imgurl }) => {
    const [colors, setColors] = useState([
        [84, 84, 84],
        [67, 67, 67],
        [26, 26, 26],
        [12, 12, 12],
        [0, 0, 0],
    ]);
    useEffect(() => {
        if (imgurl) {
            // 使用ColorThief获取图片的主要颜色
            // console.log(imgurl, 'img');
            const img = new Image();
            img.crossOrigin = 'Anonymous'; // 如果图片来自不同域，需要设置这个属性
            img.src = imgurl;
            img.onload = () => {
                const colorThief = new ColorThief();
                const palette = colorThief.getPalette(img, 5);
                // console.log(palette, 'palette');
                setColors(palette);
            };
        }
    }, [imgurl]);

    // 确保颜色数组有5个颜色
    const normalizedColors = colors
        .concat([
            [84, 84, 84],
            [67, 67, 67],
            [26, 26, 26],
            [12, 12, 12],
            [0, 0, 0],
        ])
        .slice(0, 5);
    const gradientColors = normalizedColors
        .map((color) => `rgb(${color.join(',')})`)
        .join(', ');
    const time = `${15 - (Math.random() * 5).toFixed(1)}s`;
    return (
        <div
            className="gradient-bg gradient-bg-css"
            style={{
                backgroundImage: `linear-gradient(45deg,${gradientColors})`,
                backgroundSize: '600% 100%',
                animationName: 'gradient', // 使用具体的动画名
                animationDuration: time,
                animationTimingFunction: 'linear',
                animationIterationCount: 'infinite',
                animationDirection: 'alternate', // 单独设置动画方向
            }}
        ></div>
    );
};

export default GradientBackgroundCss;
